package com.wanaofu.dao;

import java.util.List;

import org.hibernate.LockMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.wanaofu.model.AbstractBaseEntity;
import com.wanaofu.model.ProductInfo;
import com.wanaofu.model.UserInfo;
import com.wanaofu.model.Warehouse;
import com.wanaofu.model.WarehouseBalance;

@Repository 
public class QueryDAO extends AbstractBaseDAO{
	@SuppressWarnings("unchecked")
	public <T extends AbstractBaseEntity> T findEntityByID(Class<T> entityClass, String id){
		return (T)super.get(entityClass, id) ;
	}
	
	@SuppressWarnings("unchecked")
	public List<Warehouse> findWareHouseByCode(String warehouseCode) {
		return (List<Warehouse>) this.sessionFactory.getCurrentSession()
				.createQuery("from Warehouse u where u.warehouseCode = ?")
				.setString(0, warehouseCode).list();
	}
	
	public Warehouse findWareHouseByCode(String wCode,String areaCode,String shelfCode,String floorCode){
		return (Warehouse)this.sessionFactory.getCurrentSession().createCriteria(Warehouse.class)
		     .add(Restrictions.eq("warehouseCode", wCode))
		     .add(Restrictions.eq("areaCode", areaCode))
		     .add(Restrictions.eq("shelfCode", shelfCode))
		     .add(Restrictions.eq("floorCode", floorCode))
		     .uniqueResult();
	}
	
	public ProductInfo findProductInfoByCode(String pCode) {
		return (ProductInfo)this.sessionFactory.getCurrentSession().createCriteria(ProductInfo.class)
			     .add(Restrictions.eq("code", pCode))
			     .uniqueResult();
	}

	public WarehouseBalance findBalance(Warehouse wh,ProductInfo pro,String batchNo) {
		return (WarehouseBalance)this.sessionFactory.getCurrentSession().createCriteria(WarehouseBalance.class)
			     .add(Restrictions.eq("position", wh))
			     .add(Restrictions.eq("product", pro))
			     .add(Restrictions.eq("batchNo", batchNo)).setLockMode("u", LockMode.UPGRADE_NOWAIT).uniqueResult();
	}
	
	public UserInfo findUserInfoByCode(String code) {
		return (UserInfo)this.sessionFactory.getCurrentSession().createCriteria(UserInfo.class)
			     .add(Restrictions.eq("code", code)).uniqueResult();
	}

}
